package controllers;

import authentication.IMembershipProvider;
import authentication.annotations.LoginAction;
import br.com.caelum.vraptor.Get;
import br.com.caelum.vraptor.Post;
import br.com.caelum.vraptor.Resource;
import br.com.caelum.vraptor.Result;
import managers.CreateUserException;
import services.UserService;

@Resource
public class AccountController extends BaseController {

    private final IMembershipProvider membershipProvider;
    private final UserService userService;

    public AccountController(Result result, IMembershipProvider membershipProvider, UserService userService) {
        super(result, membershipProvider);
        this.membershipProvider = membershipProvider;
        this.userService = userService;
    }

    @Get
    @LoginAction
    public void login(){

    }

    @Post
    public void login(String username, String password){
        boolean loginSucceed = membershipProvider.login(username, password);
        if(loginSucceed){
            result.redirectTo(HomeController.class).index();
        }else{
            result.include("loginSucceed", loginSucceed);
        }
    }

    @Get
    public void logout(){
        membershipProvider.logout();
        result.redirectTo(HomeController.class).index();
    }

    @Get
    public void signUp(){

    }

    @Post
    public void signUp(String username, String email, String password){

        try {
            userService.createNewUser(username.trim(), email.trim(), password.trim());
        } catch (CreateUserException e) {
            result.include("succeedMessage", e.getMessage());
            return;
        }

        result.include("succeedMessage", true);
    }
}
